package com.wzy.service.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.wzy.service.service.FileService;
import com.wzy.service.util.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/3/30 18:13
 * 4
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OssProperties ossProperties;


    @Override
    public String upload(InputStream inputStream, String module, String originalFilename) {
        String endpoint = ossProperties.getEndpoint();
        String keyid = ossProperties.getKeyid();
        String keysecret = ossProperties.getKeysecret();
        String bucketname = ossProperties.getBucketname();


        OSS ossClient = new OSSClientBuilder().build(endpoint, keyid, keysecret);
        if (!ossClient.doesBucketExist(bucketname)) {
            //创建bucket
            ossClient.createBucket(bucketname);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketname, CannedAccessControlList.PublicRead);
        }

        //构建日期路径：avatar/2019/02/26/文件名
        String folder = new DateTime().toString("yyyy/MM/dd");

        //文件名：uuid.扩展名
        String fileName = UUID.randomUUID().toString();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = module + "/" + folder + "/" + fileName + fileExtension;

        //文件上传至阿里云
        ossClient.putObject(ossProperties.getBucketname(), key, inputStream);
        // https://wzy-image.oss-cn-hangzhou.aliyuncs.com/english_study/head/2021/03/31/252c84f4-04d8-4a2e-81fe-0be663dd990f.jpg
        // https://wzy-image.https://oss-cn-hangzhou.aliyuncs.com/english_study/head/2021/03/31/d58a499d-7589-4c93-993b-fe597b269396.jpg
        // 关闭OSSClient。
        ossClient.shutdown();
        System.out.println(endpoint);
        //返回url地址
        return "https://" + bucketname + "." + endpoint + "/" + key;
    }
}
